package com.pro_one.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.pro_one.dao.RoleDao;
import com.pro_one.entity.PageResult;
import com.pro_one.entity.QueryPageBean;
import com.pro_one.pojo.Role;
import com.pro_one.service.RoleService;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Service(interfaceClass = RoleService.class)
@Transactional
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleDao roleDao;

    @Override
    public Set findRolesByUserId(Integer id) {
        return null;
    }

    @Override
    public PageResult findAllRole(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(),queryPageBean.getPageSize());
        Page<Role> roles = roleDao.findAllRole(queryPageBean.getQueryString());
        return new PageResult(roles.getTotal(),roles.getResult());
    }

    @Override
    public void addRole(Role role,Integer[] permissionIds,Integer[] menuIds) {
        roleDao.addRole(role);
        Integer roleId = role.getId();
        if (permissionIds!=null&&permissionIds.length!=0) {
            for (Integer permissionId : permissionIds) {
                Map<String, Integer> map = new HashMap<>();
                map.put("roleId",roleId);
                map.put("permissionId",permissionId);
                roleDao.addRoleIdAndPermissionId(map);
            }
        }
        if (menuIds!=null&&menuIds.length!=0) {
            for (Integer menuId : menuIds) {
                Map<String, Integer> map = new HashMap<>();
                map.put("roleId",roleId);
                map.put("menuId",menuId);
                roleDao.addRoleIdAndMenuId(map);
            }
        }



    }

    @Override
    public void deleteRole(Integer id) {
        roleDao.deleteRoleAndMenuByRoleId(id);
        roleDao.deleteRoleAndPermissionByRoleId(id);
        roleDao.deleteRole(id);

    }

    @Override
    public void updateRole(Role role,Integer[] permissionIds,Integer[] menuIds) {
        Integer id = role.getId();
        roleDao.deleteRoleAndPermissionByRoleId(id);
        roleDao.deleteRoleAndMenuByRoleId(id);
        roleDao.deleteRole(id);
        addRole(role,permissionIds,menuIds);

    }

    @Override
    public PageResult findAllRoleByUserId(Integer page, Integer size, Integer userId) {
        PageHelper.startPage(page,size);
        Page<Role> allRoleByUserId = roleDao.findAllRoleByUserId(userId);
        PageResult pageResult = new PageResult(allRoleByUserId.getTotal(), allRoleByUserId.getResult());
        return pageResult;
    }
}
